package org.hepeng.workx.spring.cloud.netflix.zuul.filter;

import org.apache.commons.lang3.StringUtils;
import org.hepeng.workx.spring.cloud.netflix.ribbon.RibbonRequestContextHolder;
import org.hepeng.workx.spring.cloud.netflix.ribbon.RibbonRequestContext;
import org.hepeng.workx.util.proxy.Invocation;
import org.hepeng.workx.util.proxy.Invoker;
import org.joor.Reflect;

/**
 * 有严重 bug 会导致请求长时间阻塞等待
 * @author he peng
 */

@Deprecated
public class RibbonRoutingFilterProxy implements Invoker {

    @Override
    public Object invoke(Invocation invocation) throws Throwable {
//        if (! StringUtils.equals(invocation.getMethod().getName() , "forward")) {
//            return Reflect.on(invocation.getNative())
//                    .call(invocation.getMethod().getName() , invocation.getArgs())
//                    .get();
////            return invocation.invoke();
//        }

        Object result;
        if (StringUtils.equalsAny(invocation.getMethod().getName() , "runFilter" , "run")) {
            result = invocation.invoke();
        } else if (StringUtils.equals(invocation.getMethod().getName() , "forward")) {
            try {
                RibbonRequestContext ribbonRequestContext = RibbonRequestContext.copy(invocation.getArgs()[0]);
                RibbonRequestContextHolder.set(ribbonRequestContext);
                result = invocation.invoke();
            } finally {
                RibbonRequestContextHolder.clear();
            }
        } else {
            result = Reflect.on(invocation.getNative())
                    .call(invocation.getMethod().getName() , invocation.getArgs())
                    .get();
        }

        // runFilter

//        Object obj;
//        try {
//            RibbonRequestContext safeRibbonCommandContext = RibbonRequestContext.copy(invocation.getArgs()[0]);
//            RibbonRequestContextHolder.set(safeRibbonCommandContext);
//            obj = invocation.invoke();
//        } finally {
//            RibbonRequestContextHolder.clear();
//        }
        return result;
    }
}
